#include "GifEncode.h"
#include "OCMain/GifUtil.h"

const emscripten::val GifEncode::run(const emscripten::val &jsOptions)
{
    bool verbose = jsOptions["verbose"].as<bool>();
    int width = jsOptions["width"].as<int>();
    int height = jsOptions["height"].as<int>();
    int delay = jsOptions["delay"].as<int>();

    const emscripten::val images = jsOptions["images"];
    int numImage = images["length"].as<int>();

    if (verbose)
    {
        std::cout << "numImage:" << numImage
                  << "\twidth:" << width
                  << "\theight:" << height << "\n";
    }

    std::vector<Uint8Vector> frames;
    for (int i = 0; i < numImage; i++)
    {
        const auto& img = images[i];
        int length = img["length"].as<int>();

        Uint8Vector perFrame;
        perFrame.resize(length);

        emscripten::val view(emscripten::typed_memory_view(
            perFrame.size(),
            perFrame.data()));
        view.call<void>("set", img);

        frames.push_back(std::move(perFrame));
    }

    String gifBin = GifUtil::encode(width, height, frames.size(), delay, frames);
    return emscripten::val::global("Uint8Array").new_(emscripten::typed_memory_view(gifBin.size(), gifBin.data()));
}
